package net.starwifi.duobao.service.impl;

import net.starwifi.duobao.dto.DBTimesStockResult;
import net.starwifi.duobao.entity.*;
import net.starwifi.duobao.mvc.*;
import net.starwifi.duobao.plugin.PaymentPlugin;
import net.starwifi.duobao.repository.DBOrderRepository;
import net.starwifi.duobao.service.*;
import net.starwifi.duobao.utils.SmsUtils;
import net.starwifi.duobao.utils.StringUtils;
import net.starwifi.duobao.utils.sms.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Administrator on 2015/11/19.
 */
@Service
public class DBOrderServiceImpl extends BaseServiceImpl<DBOrder,Long> implements DBOrderService {

    @Autowired
    MemberService memberService;

    @Autowired
    DBTimesService dbTimesService;

    @Autowired
    DBOrderRepository repository;

    @Resource(name = "taskExecutor")
    private TaskExecutor taskExecutor;

    @Autowired
    DBCodeService dbCodeService;

    @Autowired
    TradeRecordService tradeRecordService;


    @Override
    public DBOrder findBySn(String sn) {
        return repository.findBySn(sn);
    }


    public void updateOrderImage(Long productId,String imageUrl){
        repository.updateOrderImage(productId,imageUrl);
    }


    @Override
    @Transactional
    public void clearException(DBTimes dbTimes){
       /* int i=0;
        if(dbTimes!=null&&dbTimes.getDbOrder()!=null){
            if(dbTimes.getIsLottery()&&dbTimes.getLotteryMobile()!=null){
                List<DBOrder> dbOrders=getListData("o.timesNo=?1 and o.isLottery=?2",new Object[]{dbTimes.getTimesNo(),Boolean.TRUE});
                for(DBOrder order:dbOrders){
                    if(!order.getId().equals(dbTimes.getDbOrder().getId())){
                        order.setIsLottery(Boolean.FALSE);
                        update(order);
                        i=i+1;
                    }
                }
                System.out.println(dbTimes.getTimesNo()+" "+i);
            }
        }*/
    }

    @Override
    @Transactional
    public DBOrder build(DBProduct dbProduct,Member member, String sn, String timesNo, Integer num,String ip,String fromAddress) {
        DBOrder order=new DBOrder();
        order.setSn(sn);
        order.setProductId(dbProduct.getId());
        order.setPhone(member.getMobile());
        order.setIsRefund(Boolean.FALSE);
        order.setMobile(member.getMobile());
        order.setDbTimes(dbTimesService.findByTimesNo(timesNo));
        order.setIp(ip);
        order.setIsLottery(Boolean.FALSE);
        order.setName(dbProduct.getName());
        order.setDescription(dbProduct.getMemo());
        order.setFromAddress(fromAddress);
        order.setQuantity(num); //订单数量
        order.setTimesNo(timesNo); //夺宝期
        order.setOrderStatus(0); //订单确认
        order.setPaymentStatus(0); //未支付
        order.setShippingStatus(0);  //等待出单
        order.setProductMedium(dbProduct.getMedium());
        order.setAmount(dbProduct.getDbTimes().getSingleAmount().multiply(BigDecimal.valueOf(num)));
        order.setPaymentMethodName("");
        order.setMemberId(member.getId());
        order.setIsPrivate(Boolean.TRUE);
//        if(dbProduct.getFlag().equals(DBProduct.FLAG_YX)){
//            order.setFlag(DBProduct.FLAG_YX);
//        }else{
//            order.setFlag(DBProduct.FLAG_DEFAULT);
//        }
        save(order);
        flush();
        return order;
    }


    @Override
    @Transactional
    public DBOrder build(DBProduct dbProduct, String sn, String timesNo, Integer num,String ip,String fromAddress,String paymentPluginId) {
        Member member=memberService.getCurrent();
        DBOrder order=new DBOrder();
        order.setSn(sn);
        order.setProductId(dbProduct.getId());
        order.setPhone(member.getMobile());
        order.setIsRefund(Boolean.FALSE);
        order.setMobile(member.getMobile());
        order.setDbTimes(dbTimesService.findByTimesNo(timesNo));
        order.setIp(ip);
        order.setIsLottery(Boolean.FALSE);
        order.setName(dbProduct.getName());
        order.setDescription(dbProduct.getMemo());
        order.setFromAddress(fromAddress);
        order.setQuantity(num); //订单数量
        order.setTimesNo(timesNo); //夺宝期
        order.setOrderStatus(0); //订单确认
        order.setPaymentStatus(0); //未支付
        order.setShippingStatus(0);  //等待出单
        order.setProductMedium(dbProduct.getMedium());
        order.setAmount(dbProduct.getDbTimes().getSingleAmount().multiply(BigDecimal.valueOf(num)));
        order.setPaymentMethodName("");
        order.setMemberId(member.getId());
        order.setPaymentMethodName(paymentPluginId);
//        if(dbProduct.getFlag().equals(DBProduct.FLAG_YX)){
//            order.setFlag(DBProduct.FLAG_YX);
//        }else{
//            order.setFlag(DBProduct.FLAG_DEFAULT);
//        }
        save(order);
        flush();
        return order;
    }


    /** 支付成功*/
    @Transactional
    public void payment(final DBOrder order, Payment payment) {
        Assert.notNull(order);
        System.out.println("支付成功！！！");
        if(order.getPaymentStatus()!=0){
            return;
        }
        order.setPaymentStatus(1); //支付成功
        order.setOrderStatus(1);
        DBTimesStockResult result=dbTimesService.lockStock(order); //分配库存
        order.setCodeInfo(result.getCodeInfo());
        order.setDistributionQuantity(result.getAllowCount()); //实际分配库存
        update(order); //更新订单
//        if(payment.getPaymentPluginId() .equals("wo3DirectPlugin")){
//            //风控通知
//           riskConService.riskNotify(order.getSn(), order.getMobile(), "riskNotify");
//        }
        if(order.getIsPrivate()==null){
            smsTask(order); //发送短信
        }
        if(result.isTimesOver()){ //开奖
            DBTimes dbTimes=dbTimesService.find(order.getDbTimes().getId());
            dbTimesService.findLottery(dbTimes);
        }
        if(result.getCount()>result.getAllowCount()){ //退款
             int c=result.getCount()-result.getAllowCount();
             BigDecimal refundsAmount= BigDecimal.valueOf(c);
             if(refundsAmount.compareTo(BigDecimal.ZERO)==1){
                  if(order.getIsPrivate()==null){
                      tradeRecordService.refunds(order.getMemberId(),refundsAmount,"1元夺宝退款",order.getSn()); //订单退款
                  }
             }
        }
    }

    /** 支付短信提示*/
    public void smsTask(final DBOrder dbOrder){
        try {
            taskExecutor.execute(new Runnable() {
                public void run() {
                    SmsUtils.sendSms(dbOrder.getMobile(),"","1729");
                    //SMSUtils.send(dbOrder.getMobile(),"http://dwz.cn/2AyW0k","10011");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Transactional
    public void autoOrderCodeInfo(){
        PageView pageView=new PageView(0,20);
        pageView.addFilter(Filter.eq("paymentStatus", 1));
        pageView.addFilter(Filter.gt("id", 3074));
        pageView.setNumPerPage(20); //每次查询20行
        Long total=getMQueryCount(pageView.getFilters()); //记录总数
        int totalPage=(int) Math.ceil((double) total / (double) 20); //总页数
        try {
            for(int i=1;i<=totalPage;i++){
                pageView.setPageNumber(i); //当前页
                Page<DBOrder> page = getScrollData(pageView);
                for (DBOrder data : page.getContent()) {
                    StringBuffer codeInfo=new StringBuffer("");
                    List<DBCode> dbCodeList=new ArrayList<DBCode>(data.getDbCodeList());
                    for(DBCode dbCode:dbCodeList){
                        codeInfo=codeInfo.append("").append(dbCode.getDbCode()).append(",");
                    }
                    data.setCodeInfo(codeInfo.toString());
                    update(data);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Autowired
    RefundsService refundsService;

    @Autowired
    PluginService pluginService;



    public void batchRefunds(HttpServletRequest request){
        PageView pageView=new PageView(0,20);
        pageView.addFilter(Filter.eq("paymentStatus", 1));
        pageView.addFilter(Filter.eq("isRefund", Boolean.FALSE));
        pageView.addFilter(Filter.eq("codeInfo", ""));
        pageView.addFilter(Filter.gt("amount", BigDecimal.valueOf(0)));
        pageView.setNumPerPage(20); //每次查询20行
        Long total=getMQueryCount(pageView.getFilters()); //记录总数
        int totalPage=(int) Math.ceil((double) total / (double) 20); //总页数
        try {
            for(int i=1;i<=totalPage;i++){
                pageView.setPageNumber(i); //当前页
                Page<DBOrder> page = getScrollData(pageView);
                for (DBOrder data : page.getContent()) {
                    refundsTr(data, request);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Transactional
    public void refundsTr(DBOrder data,HttpServletRequest request){
        try {
            Refunds refunds=refundsService.findByOrderSn(data.getSn());
            if(refunds==null){
                refunds=new Refunds();
                refunds.setSn(StringUtils.getUUID());
                refunds.setMethod(Refunds.Method.online);
                refunds.setStatus(Refunds.Status.wait);
                refunds.setPaymentMethod(data.getPaymentMethodName());
                refunds.setAmount(data.getAmount());
                refunds.setOrderId(data.getId());
                refunds.setOrderSn(data.getSn());
                refunds.setOperator("sys");
                //refunds.setFlag(data.getFlag());
                refundsService.save(refunds);
            }
            PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin("wo3DirectPlugin");
            if (paymentPlugin == null || !paymentPlugin.getIsEnabled()) {

            }else{
                net.starwifi.duobao.mvc.Message message=paymentPlugin.refund(refunds,request);
                System.out.println("backMsg:"+message.getContent());
                System.out.println(data.getId()+","+data.getMobile()+","+data.getSn()+","+data.getAmount());
                if(message.getType()== net.starwifi.duobao.mvc.Message.Type.success){ //退款成功
                    //refunds(data, refunds); //订单设置为退款
                    data.setIsRefund(Boolean.TRUE);
                    data.setPaymentStatus(2); //退款
                    data.setRefundDate(new Date());
                    update(data);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    /** 订单退款 */
    @Override
    @Transactional
    public void refunds(DBOrder order, Refunds refunds) {
        Assert.notNull(order);
        order.setIsRefund(Boolean.TRUE);
        order.setPaymentStatus(2); //退款
        order.setRefundDate(new Date());
        update(order);
    }
}
